//
// SoapTrace.Net - A soap message monitoring utility. 
//
// Copyright (C) 2005-2009 Matthew Ward
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// Matthew Ward (mrward@users.sourceforge.net)

using SoapTrace.Core.Communication;
using SoapTrace.Core.Diagnostics;
using System;
using System.IO;
using System.Net;
using System.Windows.Forms;
using System.Xml;
using WinPcap;

namespace SoapTrace
{
	/// <summary>
	/// Displays Tcp packets that have been received.
	/// </summary>
	public class PacketViewer : SoapPacketMonitorBase
	{
		PacketLogEntryCollection m_LogEntries = new PacketLogEntryCollection( );
		PacketsReceivedForm m_Form;
	
		/// <summary>
		/// Creates a new instance of the <see cref="PacketViewer"/>.
		/// </summary>
		public PacketViewer( )
		{
			base.MissedConnectionCaptureEnabled = true;
		}
		
		/// <summary>
		/// Saves the packet for viewing.
		/// </summary>
		/// <param name="sender">The event source.</param>
		/// <param name="e">The event arguments.</param>
		public void AddPacket( object sender, PacketReceivedEventArgs e )
		{
			SoapMessageMonitor Monitor = ( SoapMessageMonitor )sender;
			
			PacketLogEntry LogEntry = new PacketLogEntry( GetIPAddress( Monitor.RemoteServerIPAddress ), 
				Monitor.RemoteServerPort, 
				DateTime.Now, 
				e.Packet, 
				PacketLogEntry.Ethernet );
		
			lock( m_LogEntries.SyncRoot )
			{
				m_LogEntries.Add( LogEntry );
			}
		}
		
		/// <summary>
		/// Saves the packet for viewing.
		/// </summary>
		/// <param name="sender">The event source.</param>
		/// <param name="e">The event arguments.</param>
		public void AddIPPacket( object sender, PacketReceivedEventArgs e )
		{
			SoapMessageMonitor Monitor = ( SoapMessageMonitor )sender;
			
			PacketLogEntry LogEntry = new PacketLogEntry( GetIPAddress( Monitor.RemoteServerIPAddress ), 
				Monitor.RemoteServerPort, 
				DateTime.Now, 
				e.Packet, 
				PacketLogEntry.IP );
		
			lock( m_LogEntries.SyncRoot )
			{
				m_LogEntries.Add( LogEntry );
			}
		}
		
		/// <summary>
		/// Shows the packets received.
		/// </summary>
		/// <param name="owner">The owner of the dialog.</param>
		public void Show( IWin32Window owner )
		{
			using( m_Form = new PacketsReceivedForm( this ) )
			{
				m_Form.AddLogEntries( m_LogEntries );
				m_Form.ShowDialog( owner );
				m_Form = null;
			}
		}
		
		/// <summary>
		/// Saves the packets on display in the Tcp Packets received form.
		/// </summary>
		public void SavePackets( )
		{
			using( SaveFileDialog SaveFileDialog = new SaveFileDialog( ) )
			{
				SaveFileDialog.CheckPathExists = true;
				SaveFileDialog.CheckFileExists = false;
				SaveFileDialog.DefaultExt = ".xml";
				SaveFileDialog.ValidateNames = true;
				SaveFileDialog.Filter = "Xml files(*.xml)|*.xml|All files (*.*)|*.*";
				SaveFileDialog.FilterIndex = 0;
				
				DialogResult Result = SaveFileDialog.ShowDialog( );
				
				// Save the packets.
				
				if( Result == DialogResult.OK )
				{
					SaveAllPackets( SaveFileDialog.FileName );
				}
			}
		}
		
		/// <summary>
		/// Allows the user to load a saved file containing packet data into
		/// the PacketsReceivedForm.
		/// </summary>
		public void OpenFile( )
		{
			using( OpenFileDialog OpenFileDialog = new OpenFileDialog( ) )
			{
				OpenFileDialog.CheckPathExists = true;
				OpenFileDialog.CheckFileExists = false;
				OpenFileDialog.DefaultExt = ".xml";
				OpenFileDialog.ValidateNames = true;
				OpenFileDialog.Filter = "Xml files(*.xml)|*.xml|All files (*.*)|*.*";
				OpenFileDialog.FilterIndex = 0;
				
				DialogResult Result = OpenFileDialog.ShowDialog( );
				
				// Load the file.
				
				if( Result == DialogResult.OK )
				{
					LoadFile( OpenFileDialog.FileName );
				}
			}
			
		}
		
		/// <summary>
		/// Updates the display when a packet has been selected by the user.
		/// </summary>
		/// <param name="packet">The packet selected.</param>
		public void PacketSelected( Packet packet )
		{
			m_Form.SelectedItemText = packet.RawHex; 
		}
		
		/// <summary>
		/// Clears saved packets.
		/// </summary>
		public void Clear( )
		{
			lock( m_LogEntries.SyncRoot )
			{
				m_LogEntries.Clear( );
			}
			
			m_Form.Clear( );
		}		
		
		/// <summary>
		/// Saves all the packet information to the specified file.
		/// </summary>
		/// <param name="filename">The name of the file that will be
		/// used to store the packet information.
		/// </param>
		private void SaveAllPackets( string filename )
		{
			try
			{
				lock( m_LogEntries.SyncRoot )
				{
					PacketLogFile.Save( filename, m_LogEntries );
				}
			}
			catch( IOException Ex )
			{
				MessageBox.Show( Ex.Message );
			}
		}
		
		/// <summary>
		/// Loads the file into the packets received form.
		/// </summary>
		private void LoadFile( string filename )
		{
			try
			{
				PacketLogEntryCollection Entries = PacketLogFile.Load( filename );
				
				if( Entries.Count == 0 )
				{
					MessageBox.Show( "No packets found in file." );
				}
				else
				{
					m_Form.AddLogEntries( Entries );
					
					lock( m_LogEntries.SyncRoot )
					{
						m_LogEntries.AddRange( Entries );
					}
					
					ProcessEntries( Entries );
				}
			}
			catch( IOException Ex )
			{
				MessageBox.Show( Ex.Message );
			}			
			catch( XmlException Ex )
			{
				MessageBox.Show( Ex.Message );
			}
		}
		
		/// <summary>
		/// Processes the packets and creates soap messages which 
		/// will be displayed in the main form.
		/// </summary>
		/// <param name="entries">A collection of packet log entries.</param>
		private void ProcessEntries( PacketLogEntryCollection entries )
		{
			base.ClearClients( );
			
			foreach( PacketLogEntry Entry in entries )
			{
				base.SetFilter( GetIPAddress( Entry.RemoteServerFilter ), Entry.RemoteServerPortFilter );
				
				if( Entry.PacketType == PacketLogEntry.IP )
				{
					IPPacket IPPacket = new IPPacket( Entry.Packet.GetBytes( ) );
					base.ProcessIPPacket( IPPacket );
				}
				else
				{
					base.ProcessPacket( Entry.Packet );
				}
			}
		}
		
		/// <summary>
		/// Gets the IP address from a host name or ip address string.
		/// </summary>
		/// <param name="address">An IP address or a host name.</param>
		/// <returns>An IP address.</returns>
		private string GetIPAddress( string address )
		{
			IPAddress IPAddress = null;
			
			try
			{
				IPAddress = IPAddress.Parse( address );
			}
			catch( FormatException )
			{
				IPHostEntry HostEntry = Dns.GetHostEntry( address );
				IPAddress = TcpSocket.GetIPAddress( HostEntry );
			}
			
			return IPAddress.ToString( );
		}
	}
}
